package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.EmpQueryParam;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Student;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean list(EmpQueryParam empQueryParam) {
        //1. 设置分页参数
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());

        //2. 执行查询
        List<Clazz> clazzList = clazzMapper.list(empQueryParam);

        //3. 解析封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;

        return new PageBean(p.getTotal(),p.getResult());
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }

    @Override
    public void delete(Integer id) {
        // 如果该班级下有学生，则不能删除
        List<Student> studentList = studentMapper.findStudentByClazzId(id);
        if (!studentList.isEmpty()){
            throw new RuntimeException("对不起, 该班级下有学生, 不能直接删除");
        }
        clazzMapper.delete(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> clazzList() {
        List<Clazz> clazzList = clazzMapper.clazzList();
        return clazzList;
    }
}
